package com.bill.robot.koalacam;

import java.io.File;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

/**
 * 1:N 识别
 * @author Wangshutao
 * 2016年7月5日
 */
@SuppressWarnings("deprecation")
public class Recognize {

  /**
  * 1:N 识别
  * @param url
  * @param photo 用于识别的照片
  * @param screen_token 从 /pad/login 接口获得
  * @throws Exception
  */
  public static void recognize(String url, String photo, String screen_token) throws Exception {
    System.out.println("Start POST /recognize 1:N 识别 ...");

    // 创建默认的HttpClient
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost request = new HttpPost(url);

    // 设置识别的图片 设备的screen_token
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("image", new FileBody(new File(photo)));
    reqEntity.addPart("screen_token", new StringBody(screen_token));
    request.setEntity(reqEntity);

    CloseableHttpResponse response = httpclient.execute(request);
    String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

    // 解析JSON数据 获取识别出用户的个人信息 输出相似度
    JSONObject resp = new JSONObject(responseBody);
    JSONObject person = resp.getJSONObject("person");
    if (person != null) {
      System.out.println("confidence:" + person.getString("confidence"));
    }
  }
}